Web development and Tech news Blog site. WEBISFREE.com

HOME > webdevetc

[JavaScript] Implementing text-to-speech functionality using speechSynthesis.

Last Modified : 24 Feb, 2023 / Created : 24 Feb, 2023
724
View Count
We want to implement a speaking feature using JavaScript on a web page. Let's find out how to do it below.




# Creating a JavaScript Speaking Feature with SpeechSynthesis


It is possible to implement a speaking feature on the web using the SpeechSynthesis web API. Note that SpeechSynthesis literally means 'speech synthesis.' First, let's try implementing the feature to simply say "Hello!" To do this, we declare SpeechSynthesis in the variable mySynth.
const mySynth = window.speechSynthesis;

This instance has the method speak(), which is the most important feature for speaking. If we use simple text as the argument for this method, an error will occur as follows:
mySynth.speak('Hello');

// Result
VM2902:1 Uncaught TypeError: Failed to execute 'speak' on 'SpeechSynthesis': parameter 1 is not of type 'SpeechSynthesisUtterance'.

Looking at the error message, we can see that the first argument, 'Hello,' is not of the SpeechSynthesisUtterance type. In other words, speak() can only be used with SpeechSynthesisUtterance. What is SpeechSynthesisUtterance? This is also a web API for speaking, and it allows you to declare the most important text for speaking and set the language, speed, voice, volume, etc. to be used at the same time using SpeechSynthesisUtterance.

Let's create the simplest example and see how it works. Now, let's create an instance using the text 'Hello' with SpeechSynthesisUtterance. This time, we'll use the new keyword. Then, we use mySynth.speak(), which we created earlier, with the instance we just created.
const utterance = new SpeechSynthesisUtterance('Hello');

mySynth.speak(utterance);

If we run the above code, we can hear the speaker say "Hello." Now that we have implemented the speaking feature, let's look at some additional key options.

  • utterance.text = 'Hello Again'; // Set the text to be spoken
  • utterance.lang = 'ko'; // Set the language to Korean. English is 'en'
  • utterance.rate = 1; // (0 ~ 10) Set the speed of speaking utterance.volume
  • utterance.volume = 0.5 // (0 ~ 1) Set the size and volume of speaking
  • utterance.pitch= 0.5 // (0 ~ 2) Set the tone of speaking


These options are very useful for adjusting the spoken text or controlling the speed, tone, etc. of speaking. Please note that the size of the options set may vary depending on the value of the voice below.

To change the voice, you must use the voice option.

  • utterance.voice = speechSynthesis.getVoices()[0] // set the available voice


You need to know what voices are available. If you input speechSynthesis.getVoices(); as shown below, it will show you all the currently available voices.
speechSynthesis.getVoices();

You need to find and set the desired voice from the list that is output after execution. The list contains various voices for each language that are available.


So far, we have looked at the key options and methods for implementing speech using JavaScript. To make it easier to use, we will write a simple function below.
const speakText = function(text, options) {
  if (!text) return;
  synth = window.speechSynthesis;
  utterance = new SpeechSynthesisUtterance(text);
  if (speechSynthesis.pending) speechSynthesis.pending.cancel();
  if (options && Object.keys(options).length) {
    Object.keys(options).forEach(opt => {
      utterance[opt] = options[opt]
    })
  }
  synth.speak(utterance);
}

With this function, it will be easier to implement the speech function. We have implemented an input form using the above code. Enter the desired text and press the Speak button to try it out.

* Please enter the text to speak below.
<div>
<input id="testSpeak" />
<p>Language - lang <select id="testSpeakLang" ><option default value="ko">Korean</option><option value="en">English</option></select></p>
<p>Speed - rate <input type="number" max="10" min="0" id="testSpeakRate" value="1" /></p>
<p>Volume - volume <input type="number" max="1" min="0" id="testSpeakVolume" value="0.5" /></p>
<p>Tone - pitch <input type="number" max="2" min="0.5" id="testSpeakPitch" value="1" /></p>
</div>
<button onclick="runSpeakText()">Speak</button>
<script>
window.speakText = function(text, options) {
if (!text) return;
synth = window.speechSynthesis;
utterance = new SpeechSynthesisUtterance(text);
if (speechSynthesis.pending) speechSynthesis.pending.cancel();
if (options && Object.keys(options).length) {
Object.keys(options).forEach(opt => {
utterance[opt] = options[opt]
})
}
synth.speak(utterance);
};
window.runSpeakText = function() {
const testText = document.getElementById('testSpeak').value;
const testTextLang = document.getElementById('testSpeakLang').value;
const testTextRate = document.getElementById('testSpeakRate').value;
const testTextPitch = document.getElementById('testSpeakPitch').value;
const testTextVolume = document.getElementById('testSpeakVolume').value;
speakText(testText, { lang: testTextLang, rate: testTextRate, pitch: testTextPitch, volume: testTextVolume  });
};
</script>



The above function makes it easier to use by simply entering the text to be spoken or setting options.

@ Speak just the text
speakText('Hello Webisfree.com.')


@ Increase or decrease volume
speakText('Hello Webisfree.com.', { volume: 0.3 })
speakText('Hello Webisfree.com.', { volume: 1 })


@ Speak faster
speakText('Hello! Webisfree.com.', { rate: 2 })


@ Raise or lower pitch
speakText('Hello! Webisfree.com.', { pitch: 0.8 })
speakText('Hello! Webisfree.com.', { pitch: 1.5 })


@ Raise or lower pitch
speakText('Hello Webisfree.com!', { voice: speechSynthesis.getVoices()[0] })


Multiple options can be set together at once.
speakText('Hello! Webisfree.com.', { volume: 0.5, pitch: 1.5 })
speakText('Hello Webisfree.com!', { volume: 1, rate: 1.2, voice: speechSynthesis.getVoices()[1] })

By the way, the following code is an additional code to cancel the previous command and reuse it if there is an error or pending command.
if (speechSynthesis.pending) speechSynthesis.pending.cancel();


So far, we have created a function to speak text on a web browser using JavaScript.

Perhaps you're looking for the following text as well?

Previous

[Nuxtjs] Dynamically refreshing useFetch() with parameter and query string changes